package it.geosolutions.geoserver.rest.decoder;

import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.jdom.Element;

import it.geosolutions.geoserver.rest.decoder.utils.JDOMBuilder;
import it.geosolutions.geoserver.rest.manager.GeoServerRESTSecurityManager;

public class RESTDataRules {
    
    private static String RESOURCE = "resource";
    
    private final Element rulesElem;

    /**
     * Build a RESTRules from a REST response.
     *
     * @param response XML representation of the rule.
     * @return a new RESTRules, or null if XML could not be parsed.
     */
    public static RESTDataRules build(String response) {
        if (response == null) {
            return null;
        }

        Element pb = JDOMBuilder.buildElement(response);
        if (pb != null) {
            return new RESTDataRules(pb);
        } else {
            return null;
        }
    }
    
    /**
     * Create a RESTRule from a XML element.
     *
     * @param elem The jdom XML Element describing a rule.
     */
    public RESTDataRules(Element elem) {
        this.rulesElem = elem;
    }
    
    /**
     * Return the roles for a rule
     * 
     * @param workspace
     * @param layer
     * @param type
     * @return list of roles, empty list for any role (*), null if no rule
     */
    public Set<String> getRule(String workspace, String layer, GeoServerRESTSecurityManager.RuleType type) {
        String ruleResource = GeoServerRESTSecurityManager.resource(workspace, layer, type);
        for (Object o : rulesElem.getChildren()) {
            Element child = (Element) o;
            if (ruleResource.equals(child.getAttributeValue("resource"))) {
                if (GeoServerRESTSecurityManager.ANY.equals(child.getText())) {
                    return Collections.emptySet();
                } else {
                    return new HashSet<String>(Arrays.asList(child.getText().split(",")));
                }
            }
        }
        return null;
    }

}
